<template>
  <view class="upform">
    <up-subsection
      :list="tabList"
      mode="button"
      fontSize="16"
      @change="changeClick"
      bold
      :current="0"
    ></up-subsection>
    <up-form
      labelPosition="left"
      :model="modelForm"
      :rules="modelForm.rules"
      ref="formRef"
    >
      <!-- <up-form-item prop="userInfo.pilot">
        <view class="registration-type-buttons">
          <view class="registration-button active" @click="selectPilot">
            <up-icon name="grid" color="#4b93ff" size="25px"></up-icon>
            <text class="registration-text">飞手注册</text>
          </view>
          <view class="registration-button" @click="selectOrganization">
            <up-icon name="grid" color="#4b93ff" size="25px"></up-icon>
            <text class="registration-text">组织注册</text>
          </view>
        </view>
      </up-form-item> -->
      <up-form-item prop="userInfo.phone">
        <view class="userInfo-phone">
          <text>手机号码</text>
          <view class="phone-input">
            <up-input
              prefixIcon="phone"
              cursorColor="red"
              border="none"
              :prefixIconStyle="prefixIconStyle"
              size="large"
              :customStyle="customStyle"
              placeholder="请输入手机号"
              v-model="modelForm.userInfo.phone"
              @blur="validatePhone"
              @input="onPhoneInput"
            ></up-input>
            <view class="wrap">
              <up-toast ref="uToastRef"></up-toast>
              <up-code
                :seconds="60"
                @end="end"
                @start="start"
                ref="uCodeRef"
                @change="codeChange"
              ></up-code>
              <up-button
                color="#0066ff"
                :disabled="disabled"
                :customStyle="{
                  height: '30px',
                  borderRadius: '8px',
                }"
                @tap="getCode"
                >{{ tips }}</up-button
              >
            </view>
          </view>
          <view v-if="phoneTouched && phoneError" class="password-error-tip">{{ phoneError }}</view>
        </view>
      </up-form-item>
      <!-- <up-button
        type="primary"
        :customStyle="{
          height: '40px',
          borderRadius: '6px',
          marginTop: '10px',
        }"
        color="#1989fa"
        text="获取微信手机号"
      ></up-button> -->
      <up-form-item prop="userInfo.code">
        <view class="userInfo-phone">
          <text>验证码</text>
          <view class="phone-input">
            <up-input
              cursorColor="red"
              border="none"
              :prefixIconStyle="prefixIconStyle"
              :customStyle="customStyle"
              placeholder="请输入验证码"
              v-model="modelForm.userInfo.code"
              @blur="validateCode"
              @input="onCodeInput"
            ></up-input>
          </view>
          <view v-if="codeTouched && codeError" class="password-error-tip">{{ codeError }}</view>
        </view>
      </up-form-item>
      <up-form-item prop="userInfo.password">
        <view class="userInfo-phone">
          <text>密码</text>
          <view class="phone-input">
            <up-input
              prefixIcon="lock"
              size="large"
              border="none"
              :customStyle="customStyle"
              :prefixIconStyle="prefixIconStyle"
              placeholder="请设置密码（8-20位，含大小写字母和数字）"
              :password="true"
              v-model="modelForm.userInfo.password"
              @blur="validatePassword"
              @input="onPasswordInput"
            ></up-input>
          </view>
          <view v-if="passwordTouched && passwordError" class="password-error-tip">{{ passwordError }}</view>
        </view>
      </up-form-item>
      <up-form-item prop="userInfo.confirmPassword">
        <view class="userInfo-phone">
          <text>确认密码</text>
          <view class="phone-input">
            <up-input
              prefixIcon="lock"
              size="large"
              border="none"
              :prefixIconStyle="prefixIconStyle"
              :customStyle="customStyle"
              placeholder="请再次输入密码"
              :password="true"
              v-model="modelForm.userInfo.confirmPassword"
              @blur="validateConfirmPassword"
              @input="onConfirmPasswordInput"
            ></up-input>
          </view>
          <view v-if="confirmPasswordTouched && confirmPasswordError" class="password-error-tip">{{ confirmPasswordError }}</view>
        </view>
      </up-form-item>
      <up-form-item prop="userInfo.userName">
        <view class="userInfo-phone">
          <text>姓名</text>
          <view class="phone-input">
            <up-input
              cursorColor="red"
              border="none"
              prefixIcon="account"
              :prefixIconStyle="prefixIconStyle"
              :customStyle="customStyle"
              placeholder="请输入真实姓名（用于证书认证）"
              v-model="modelForm.userInfo.userName"
              @blur="validateUserName"
              @input="onUserNameInput"
            ></up-input>
          </view>
          <view v-if="userNameTouched && userNameError" class="password-error-tip">{{ userNameError }}</view>
        </view>
      </up-form-item>
      <up-form-item prop="userInfo.sex">
        <view class="userInfo-phone">
          <text>性别</text>
          <view class="phone-input">
            <up-radio-group
              v-model="modelForm.userInfo.sex"
            >
              <up-radio
                :customStyle="{marginBottom: '8px'}"
                v-for="(item, index) in radiolist1"
                :key="index"
                :label="item.name"
                :name="item.name"
              >
              </up-radio>
            </up-radio-group>
          </view>
        </view>
      </up-form-item>


      <up-form-item prop="userInfo.age">
        <view class="userInfo-phone">
          <text>年龄</text>
          <view class="phone-input">
            
            <up-input
              type="number"
              border="none"
              :customStyle="customStyle"
              placeholder="请输入年龄"
              v-model="modelForm.userInfo.age"
              @blur="validateAge"
              @input="onAgeInput"
            ></up-input>
          </view>
          <view v-if="ageTouched && ageError" class="password-error-tip">{{ ageError }}</view>
        </view>
      </up-form-item>



      <up-form-item prop="userInfo.feiling">
        <view class="userInfo-phone">
          <text>飞龄</text>
          <view class="phone-input">
            
            <up-input
              type="number"
              border="none"
              :customStyle="customStyle"
              placeholder="请输入飞龄"
              v-model="modelForm.userInfo.feiling"
              @blur="validateFeiling"
              @input="onFeilingInput"
            ></up-input>
          </view>
          <view v-if="feilingTouched && feilingError" class="password-error-tip">{{ feilingError }}</view>
        </view>
      </up-form-item>




      <!-- <up-form-item prop="userInfo.organizationName">
        <view class="userInfo-phone">
          <text>组织名称</text>
          <view class="phone-input">
            <up-input
              cursorColor="red"
              border="none"
              prefixIcon="account"
              :prefixIconStyle="prefixIconStyle"
              :customStyle="customStyle"
              placeholder="请输入公司名称（用于证书认证）"
              v-model="modelForm.userInfo.organizationName"
            ></up-input>
          </view>
        </view>
      </up-form-item> -->
      <view class="id-card">
        <text class="upload-title">身份证照片</text>
        <up-form-item prop="userInfo.frontSideIDCard">
          <view class="userInfo-phone">
            <text>身份证正面</text>
            <upload
              :uploadIcon="'arrow-upward'"
              uploadType="idcard_front"
              v-model:uploadMd5="modelForm.userInfo.frontSideIDCard"
            >
              <template #text>
                <text>上传正面照片</text>
              </template>
            </upload>
          </view>
          <view v-if="frontIDCardTouched && frontIDCardError" class="password-error-tip">{{ frontIDCardError }}</view>
        </up-form-item>
        <up-form-item prop="userInfo.reverseSideIDCard">
          <view class="userInfo-phone">
            <text>身份证反面</text>
            <upload
              :uploadIcon="'arrow-upward'"
              uploadType="idcard_back"
              v-model:uploadMd5="modelForm.userInfo.reverseSideIDCard"
            >
              <template #text>
                <text>上传反面照片</text>
              </template>
            </upload>
          </view>
          <view v-if="backIDCardTouched && backIDCardError" class="password-error-tip">{{ backIDCardError }}</view>
        </up-form-item>
      </view>
      <view class="id-card">
        <text class="upload-title">保险信息</text>
        <up-form-item prop="userInfo.insurancePolicy">
          <view class="userInfo-phone">
            <text>保单（三者）</text>
            <upload
              :uploadIcon="'arrow-upward'"
              uploadType="exploration"
              v-model:uploadMd5="modelForm.userInfo.insurancePolicy"
            >
              <template #text>
                <text>上传保单</text>
              </template>
            </upload>
          </view>
          <view v-if="insuranceTouched && insuranceError" class="password-error-tip">{{ insuranceError }}</view>
        </up-form-item>
      </view>
 
    <up-form-item prop="userInfo.businessLicense">
      <view class="userInfo-phone">
        <view class="qualification">
          <text>个人证书/资质证明</text>
          <text>({{modelForm.userInfo?.businessLicense?.split(',')?.length || 0}}/5)</text>
        </view>
        <upload
          :maxCount="5"
          uploadType="qualification"
          v-model:uploadMd5="modelForm.userInfo.businessLicense"
        >
          <template #text>
            <text>添加证书（pdf或jpg）</text>
          </template>
        </upload>
        <view class="qualification-text">
          请至少上传应该飞手证书，可上传多个证书（最多五个）
        </view>
        <view v-if="businessLicenseTouched && businessLicenseError" class="password-error-tip">{{ businessLicenseError }}</view>
      </view>
    </up-form-item>

   </up-form>
    <view class="footer-text footer-top">
      <text>注册即代表您同意 《用户协议》和 《隐私政策》</text>
    </view>
    <up-button
      type="primary"
      :customStyle="{
        height: '40px',
        borderRadius: '6px',
        marginTop: '20px',
        marginBottom: '20px',
      }"
      color="#1989fa"
      @click="submit"
      text="注册"
    ></up-button>
    
    <view class="footer-text">
      <text>如遇到注册问题，</text>
      <text class="text-color">请联系客服</text>
    </view>
  </view>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { useStore } from "@/store/index";
import upload from "@/components/upload.vue";
import { registerPilot, checkPhone, checkUserName, checkAge, checkFlightYears } from "@/api/register";


const tabList = ref(["飞手注册", "组织注册"]);
const emit = defineEmits<{
  (e: "ontg", value: any): void
}>()
// 基本案列数据
const radiolist1 = reactive([
  {
    name: '男',
    disabled: false,
  },
  {
    name: '女',
    disabled: false,
  }
]);

// up-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
const radiovalue1 = ref('苹果');

const store = useStore();
const formRef = ref<any>(null);
const disabled = ref<any>(false);
const fileList = ref<any>([]);
const modelWidth = ref<any>();
console.log("store", store);
const modelForm = ref<any>({
  userInfo: {
    pilot: "飞手注册",
    mobile: "",
    password: "",
    sex:'男',
  },
  rules: {
    "userInfo.pilot": {
      type: "string",
      required: true,
      message: "请填写飞手注册",
      trigger: ["blur", "change"],
    },
    "userInfo.phone": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.code": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.password": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.confirmPassword": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.userName": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.sex": {
      type: "string",
      required: true,
      message: "请选择性别",
      trigger: ["blur", "change"],
    },
    "userInfo.age": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.feiling": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.frontSideIDCard": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.reverseSideIDCard": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.insurancePolicy": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.businessLicense": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.organizationName": {
      type: "string",
      required: true,
      message: "请输入组织名称",
      trigger: ["blur", "change"],
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback(new Error("请输入组织名称"));
        } else if (value.length < 2 || value.length > 15) {
          callback(new Error("组织名称长度必须在2-15位之间"));
        } else if (!/^[\u4e00-\u9fa5a-zA-Z\s]+$/.test(value)) {
          callback(new Error("组织名称只能包含中文、英文和空格"));
        } else {
          callback();
        }
      }
    },
    // "userInfo.businessLicense": {
    //   type: "string",
    //   required: true,
    //   message: "请上传营业执照",
    //   trigger: ["blur", "change"],
    // },
    // "userInfo.frontSideIDCard": {
    //   type: "string",
    //   required: true,
    //   message: "请上传身份证正面",
    //   trigger: ["blur", "change"],
    // },
    // "userInfo.reverseSideIDCard": {
    //   type: "string",
    //   required: true,
    //   message: "请上传身份证反面",
    //   trigger: ["blur", "change"],
    // },
    // "userInfo.insurancePolicy": {
    //   type: "string",
    //   required: true,
    //   message: "请上传保单",
    //   trigger: ["blur", "change"],
    // },
  },
});
const customStyle = ref<any>({
  height: "30px",
});
const prefixIconStyle = ref<any>({
  fontSize: "25px",
  color: "#9ca3af",
});
const count = ref<any>(0);
const tips = ref("");
const uCodeRef = ref<any>(null);
const phoneError = ref(""); // 手机号错误提示
const phoneTouched = ref(false); // 手机号是否已触碰
const codeError = ref(""); // 验证码错误提示
const codeTouched = ref(false); // 验证码是否已触碰
const passwordError = ref(""); // 密码错误提示
const confirmPasswordError = ref(""); // 确认密码错误提示
const passwordTouched = ref(false); // 密码是否已触碰
const confirmPasswordTouched = ref(false); // 确认密码是否已触碰
const userNameError = ref(""); // 姓名错误提示
const userNameTouched = ref(false); // 姓名是否已触碰
const ageError = ref(""); // 年龄错误提示
const ageTouched = ref(false); // 年龄是否已触碰
const feilingError = ref(""); // 飞龄错误提示
const feilingTouched = ref(false); // 飞龄是否已触碰
const frontIDCardError = ref(""); // 身份证正面错误提示
const frontIDCardTouched = ref(false); // 身份证正面是否已触碰
const backIDCardError = ref(""); // 身份证反面错误提示
const backIDCardTouched = ref(false); // 身份证反面是否已触碰
const insuranceError = ref(""); // 保单错误提示
const insuranceTouched = ref(false); // 保单是否已触碰
const businessLicenseError = ref(""); // 证书错误提示
const businessLicenseTouched = ref(false); // 证书是否已触碰

const codeChange = (text: any) => {
  console.log("text", text);
  tips.value = text;
};

// 手机号输入时的实时验证（只在已触碰后才验证）
const onPhoneInput = () => {
  if (phoneTouched.value) {
    validatePhone();
  }
};

// 手机号格式验证
const validatePhone = () => {
  phoneTouched.value = true;
  const phone = modelForm.value.userInfo.phone;
  
  if (!phone) {
    phoneError.value = "请输入手机号";
    return;
  }
  
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    phoneError.value = "请输入正确的手机号码";
    return;
  }
  
  phoneError.value = "";
};

// 验证码输入时的实时验证
const onCodeInput = () => {
  if (codeTouched.value) {
    validateCode();
  }
};

// 验证码格式验证
const validateCode = () => {
  codeTouched.value = true;
  const code = modelForm.value.userInfo.code;
  
  if (!code) {
    codeError.value = "请输入验证码";
    return;
  }
  
  if (code.length !== 4 && code.length !== 6) {
    codeError.value = "验证码必须是4位或6位";
    return;
  }
  
  codeError.value = "";
};

// 姓名输入时的实时验证
const onUserNameInput = () => {
  if (userNameTouched.value) {
    validateUserName();
  }
};

// 姓名格式验证
const validateUserName = () => {
  userNameTouched.value = true;
  const userName = modelForm.value.userInfo.userName;
  
  if (!userName) {
    userNameError.value = "请输入姓名";
    return;
  }
  
  // 验证是否为中文字符
  if (!/^[\u4e00-\u9fa5]+$/.test(userName)) {
    userNameError.value = "姓名只能是中文";
    return;
  }
  
  if (userName.length < 2 || userName.length > 5) {
    userNameError.value = "姓名必须是2-5位中文";
    return;
  }
  
  userNameError.value = "";
};

// 年龄输入时的实时验证
const onAgeInput = () => {
  if (ageTouched.value) {
    validateAge();
  }
};

// 年龄格式验证
const validateAge = () => {
  ageTouched.value = true;
  const age = modelForm.value.userInfo.age;
  
  if (!age) {
    ageError.value = "请输入年龄";
    return;
  }
  
  const ageNum = parseInt(age);
  if (isNaN(ageNum) || ageNum < 16 || ageNum > 80) {
    ageError.value = "年龄必须在16-80岁之间";
    return;
  }
  
  ageError.value = "";
};

// 飞龄输入时的实时验证
const onFeilingInput = () => {
  if (feilingTouched.value) {
    validateFeiling();
  }
};

// 飞龄格式验证
const validateFeiling = () => {
  feilingTouched.value = true;
  const feiling = modelForm.value.userInfo.feiling;
  
  if (!feiling) {
    feilingError.value = "请输入飞龄";
    return;
  }
  
  const feilingNum = parseInt(feiling);
  if (isNaN(feilingNum) || feilingNum < 0 || feilingNum > 50) {
    feilingError.value = "飞龄必须在0-50年之间";
    return;
  }
  
  feilingError.value = "";
};

// 密码输入时的实时验证（只在已触碰后才验证）
const onPasswordInput = () => {
  if (passwordTouched.value) {
    validatePassword();
  }
};

// 确认密码输入时的实时验证（只在已触碰后才验证）
const onConfirmPasswordInput = () => {
  if (confirmPasswordTouched.value) {
    validateConfirmPassword();
  }
};

// 密码格式验证
const validatePassword = () => {
  passwordTouched.value = true; // 标记为已触碰
  const password = modelForm.value.userInfo.password;
  
  if (!password) {
    passwordError.value = "请输入密码";
    return;
  }
  
  if (password.length < 8 || password.length > 20) {
    passwordError.value = "密码长度必须为8-20位";
    return;
  }
  
  const hasUpperCase = /[A-Z]/.test(password);
  const hasLowerCase = /[a-z]/.test(password);
  const hasNumber = /[0-9]/.test(password);
  
  if (!hasUpperCase || !hasLowerCase || !hasNumber) {
    passwordError.value = "密码必须同时包含大写字母、小写字母和数字";
    return;
  }
  
  passwordError.value = "";
  
  // 如果确认密码已经输入，也要重新验证
  if (confirmPasswordTouched.value && modelForm.value.userInfo.confirmPassword) {
    validateConfirmPassword();
  }
};

// 确认密码验证
const validateConfirmPassword = () => {
  confirmPasswordTouched.value = true; // 标记为已触碰
  const confirmPassword = modelForm.value.userInfo.confirmPassword;
  
  if (!confirmPassword) {
    confirmPasswordError.value = "请输入确认密码";
    return;
  }
  
  // 只有在密码格式正确的情况下，才验证两次密码是否一致
  if (passwordError.value) {
    confirmPasswordError.value = "";
    return;
  }
  
  if (confirmPassword !== modelForm.value.userInfo.password) {
    confirmPasswordError.value = "两次输入的密码不一致";
    return;
  }
  
  confirmPasswordError.value = "";
};

const getCode = () => {
  if (uCodeRef.value.canGetCode) {
    // 直接跳过验证码发送，显示成功提示
    uni.$u.toast("验证码已发送");
    // 通知验证码组件内部开始倒计时
    uCodeRef.value.start();
  } else {
    uni.$u.toast("倒计时结束后再发送");
  }
};

const end = () => {
  disabled.value = false;
};

const start = () => {
  count.value = 0;
  disabled.value = true;
};

 const changeClick = (val: any) => {
  if(val === 1){
    emit('ontg', 2);
  }
  console.log("val", val);

  // emit('ontg', 2);
};


const submit = async () => {
  try {
    // 触发所有字段的验证
    phoneTouched.value = true;
    codeTouched.value = true;
    passwordTouched.value = true;
    confirmPasswordTouched.value = true;
    userNameTouched.value = true;
    ageTouched.value = true;
    feilingTouched.value = true;
    frontIDCardTouched.value = true;
    backIDCardTouched.value = true;
    insuranceTouched.value = true;
    businessLicenseTouched.value = true;
    
    // 执行所有验证函数
    validatePhone();
    validateCode();
    validatePassword();
    validateConfirmPassword();
    validateUserName();
    validateAge();
    validateFeiling();
    
    // 检查是否有任何错误
    if (phoneError.value) {
      uni.$u.toast(phoneError.value);
      return;
    }
    if (codeError.value) {
      uni.$u.toast(codeError.value);
      return;
    }
    if (passwordError.value) {
      uni.$u.toast(passwordError.value);
      return;
    }
    if (confirmPasswordError.value) {
      uni.$u.toast(confirmPasswordError.value);
      return;
    }
    if (userNameError.value) {
      uni.$u.toast(userNameError.value);
      return;
    }
    if (ageError.value) {
      uni.$u.toast(ageError.value);
      return;
    }
    if (feilingError.value) {
      uni.$u.toast(feilingError.value);
      return;
    }
    if (frontIDCardError.value) {
      uni.$u.toast(frontIDCardError.value);
      return;
    }
    if (backIDCardError.value) {
      uni.$u.toast(backIDCardError.value);
      return;
    }
    if (insuranceError.value) {
      uni.$u.toast(insuranceError.value);
      return;
    }
    if (businessLicenseError.value) {
      uni.$u.toast(businessLicenseError.value);
      return;
    }
    
    // 表单验证（检查其他字段如姓名、性别等）
    const valid = await formRef.value.validate();
    if (!valid) {
      uni.$u.toast("请检查并完善所有必填信息");
      return;
    }

    // 准备注册数据
    const registerData = {
      userType: "1", // 飞手注册
      userName: modelForm.value.userInfo.userName,
      phone: modelForm.value.userInfo.phone,
      password: modelForm.value.userInfo.password,
      confirmPassword: modelForm.value.userInfo.confirmPassword,
      realName: modelForm.value.userInfo.userName, // 真实姓名
      sex: modelForm.value.userInfo.sex === '男' ? '0' : '1',
      age: parseInt(modelForm.value.userInfo.age),
      flightYears: parseInt(modelForm.value.userInfo.feiling),
      idCardFront: modelForm.value.userInfo.frontSideIDCard,
      idCardBack: modelForm.value.userInfo.reverseSideIDCard,
      qualification: modelForm.value.userInfo.businessLicense,
      explorationInfo: modelForm.value.userInfo.insurancePolicy,
      emergencyContact: "紧急联系人", // 临时值
      emergencyPhone: modelForm.value.userInfo.phone, // 使用相同手机号
      captcha: modelForm.value.userInfo.code,
      uuid: "temp-uuid" // 临时UUID
    };

    console.log('发送注册数据:', registerData);

    // 显示加载提示
    uni.showLoading({
      title: '注册中...',
      mask: true
    });

    // 调用飞手注册接口
    const result = await registerPilot(registerData);
    
    uni.hideLoading();
    console.log('注册响应:', result);
    
    if (result.data && result.data.code === 200) {
      uni.showToast({
        title: '注册成功，请等待审核',
        icon: 'success',
        duration: 2000
      });
      // 注册成功后跳转到登录页面
      setTimeout(() => {
        uni.navigateBack();
      }, 2000);
    } else {
      // 处理具体的错误信息
      const errorMsg = result.data?.msg || "注册失败";
      
      // 检查是否是用户名重复的错误
      if (errorMsg.includes('用户名') && errorMsg.includes('已存在')) {
        uni.showToast({
          title: '用户名已被使用，请换一个',
          icon: 'none',
          duration: 2500
        });
      } else if (errorMsg.includes('手机号') && errorMsg.includes('已存在')) {
        uni.showToast({
          title: '该手机号已注册',
          icon: 'none',
          duration: 2500
        });
      } else {
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2500
        });
      }
    }
  } catch (error: any) {
    uni.hideLoading();
    console.error('注册失败:', error);
    
    // 处理网络错误或其他异常
    let errorMessage = "注册失败，请重试";
    
    if (error.data && error.data.msg) {
      errorMessage = error.data.msg;
      
      // 特殊处理用户名重复错误
      if (errorMessage.includes('用户名') && errorMessage.includes('已存在')) {
        errorMessage = '用户名已被使用，请换一个';
      } else if (errorMessage.includes('手机号') && errorMessage.includes('已存在')) {
        errorMessage = '该手机号已注册';
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    uni.showToast({
      title: errorMessage,
      icon: 'none',
      duration: 2500
    });
  }
};


// 监听上传字段变化
watch(() => modelForm.value.userInfo.frontSideIDCard, (newVal) => {
  if (frontIDCardTouched.value || newVal) {
    frontIDCardTouched.value = true;
    if (!newVal) {
      frontIDCardError.value = "请上传身份证正面照片";
    } else {
      frontIDCardError.value = "";
    }
  }
});

watch(() => modelForm.value.userInfo.reverseSideIDCard, (newVal) => {
  if (backIDCardTouched.value || newVal) {
    backIDCardTouched.value = true;
    if (!newVal) {
      backIDCardError.value = "请上传身份证反面照片";
    } else {
      backIDCardError.value = "";
    }
  }
});

watch(() => modelForm.value.userInfo.insurancePolicy, (newVal) => {
  if (insuranceTouched.value || newVal) {
    insuranceTouched.value = true;
    if (!newVal) {
      insuranceError.value = "请上传保单照片";
    } else {
      insuranceError.value = "";
    }
  }
});

watch(() => modelForm.value.userInfo.businessLicense, (newVal) => {
  if (businessLicenseTouched.value || newVal) {
    businessLicenseTouched.value = true;
    if (!newVal) {
      businessLicenseError.value = "请至少上传一个飞手证书";
    } else {
      businessLicenseError.value = "";
    }
  }
});

onMounted(() => {
  uni.getSystemInfo({
    success: (res) => {
      modelWidth.value = res.screenWidth - 40 + "px";
    },
  });
});


const selectPilot = () => {
  // 飞手注册已经是当前状态，不需要切换
};

const selectOrganization = () => {
  emit('ontg', 2);
};
</script>
<style lang="scss" scoped>
.upform {
  .registration-type-buttons {
    display: flex;
    flex-direction: column;
    gap: 10px;
    
    .registration-button {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      background-color: #fff;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &.active {
        border-color: #4b93ff;
        background-color: #f8f9ff;
      }
      
      .registration-text {
        margin-left: 12px;
        font-size: 16px;
        color: #333;
      }
    }
  }
  
  .userInfo-phone {
    display: flex;
    flex-direction: column;
    width: 100%;
    text {
      margin-bottom: 5px;
    }
    .phone-input {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #f5f5f5;
      border-radius: 4px;
      padding: 2px 10px;
    }
  }
  .footer-text {
    text-align: center;
    font-size: 14px;
    color: #a9abaa;
    &.footer-top {
      margin-top: 50px;
    }
    .text-color {
      color: #1989fa;
    }
  }
  .qualification {
    padding-bottom: 5px;
    text {
      &:last-child {
        color: #1481ff;
        padding: 0 5px;
      }
    }
  }
}
.qualification-text {
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #bcbdc0;
  padding-top: 5px;
}

.password-error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  padding-left: 5px;
}

</style>
